package com.pine.app.module.security.core.authorize.intercept;


import com.pine.app.module.security.core.authorize.manager.MethodAuthorizeDataManager;
import com.pine.app.module.security.core.authorize.manager.ResourceAuthorizeManager;
import com.pine.app.module.security.core.authorize.manager.impl.DefaultMethodAuthorizeDataManagerImpl;
import lombok.extern.slf4j.Slf4j;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.beans.factory.annotation.Autowired;

import java.lang.reflect.Method;
import java.util.Set;


/**
 * @author xiaoyuan
 * @create 2019/9/2 13:55
 **/
@Slf4j
public class MethodAuthorizeInterceptor implements MethodInterceptor {



    private final MethodAuthorizeDataManager methodAuthorizeDataManager  = new DefaultMethodAuthorizeDataManagerImpl();


    private ResourceAuthorizeManager resourceAuthorizeManager;


    @Autowired
    public void setResourceAuthorizeManager(ResourceAuthorizeManager resourceAuthorizeManager) {
        this.resourceAuthorizeManager = resourceAuthorizeManager;
    }

    @Override
    public Object invoke(MethodInvocation invocation) throws Throwable {
        Class<?> target = invocation.getThis().getClass();
        Method method = invocation.getMethod();
        Set<String> resource = methodAuthorizeDataManager.getResources();
        resource.addAll(methodAuthorizeDataManager.getScopes());
        resourceAuthorizeManager.authorize(resource,target,method);
        return invocation.proceed();
    }

}
